﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using Microsoft.Win32;
using Pages;
using WeiBeeCommon.Core;
using WeiBeeCommon.DataTypes;
using SinaUser = Pages.SinaUser;
using System.Diagnostics;

namespace Core.Pages
{
    /// <summary>
    /// Interaction logic for FaWeiBo.xaml
    /// </summary>
    public partial class FaWeiBo : Window
    {
        public FaWeiBo()
        {
            InitializeComponent();
        }

        private WeiBeeAccountHelper accountHelper = new WeiBeeAccountHelper();
        private List<WeiBeeAccount> accounts;
        private List<IWeiBee> weibees = new List<IWeiBee>();
        private int currentWeibee;
        private void Init()
        {
            accounts = accountHelper.LoadAccounts();
            currentWeibee = 0;
            foreach (var weiBeeAccount in accounts)
            {
                var wb = WeiBeeFactory.CreateWeiBeeByType(weiBeeAccount.UserType);
                wb.SetOAuth(weiBeeAccount.Token, weiBeeAccount.TokenSecret);
                weibees.Add(wb);
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Init();
            tbText.Focus();
            bgwTwitter.DoWork += BgwTwitter_DoWork;
            bgwTwitter.RunWorkerCompleted += BgwTwitter_RunWorkerCompleted;
        }

        void BgwTwitter_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if(successful || retries==3)
            {
                TryDoNextWeiBee();
            }
            else if(retries < 3)
            {
                retries++;
                bgwTwitter.RunWorkerAsync();
            }
        }

        private void TryDoNextWeiBee()
        {
            currentWeibee++;
            if(currentWeibee < weibees.Count)
            {
                bgwTwitter.RunWorkerAsync();
            }
            else if(currentWeibee==weibees.Count)
            {
                currentWeibee = 0;
                retries = 0;
                MessageBox.Show("微博发布成功，小蜜蜂辛苦了!");
                imagefile = string.Empty;
                messagetxt = string.Empty;
            }
        }

        private bool successful = false;
        private int retries = 0;
        void BgwTwitter_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (weibees[currentWeibee].IsEnabled)
                {
                    Twitter(messagetxt, imagefile);
                    
                }
                successful = true;
            }
            catch
            {
                successful = false;
            }
        }

        private void Twitter(string txt, string img)
        {
            if (string.IsNullOrEmpty(img))
            {
                weibees[currentWeibee].AddTwitter(txt);
            }
            else
            {
                weibees[currentWeibee].AddPicture(txt, img);    
            }
        }

        BackgroundWorker bgwTwitter = new BackgroundWorker();
        private void btGood_Click(object sender, RoutedEventArgs e)
        {
            messagetxt = "我正在使用#小蜜蜂#发微博桌面版，您也来在线下载使用吧 http://winwebo.codeplex.com/releases/view/64528";
            // imagefile = @"D:\Private\7.JPG";
            bgwTwitter.RunWorkerAsync();
        }

        private string messagetxt;
        private string imagefile;

        private void btQQ_Click(object sender, RoutedEventArgs e)
        {
            if (HasAccountType(WeiBeeType.QQ))
            {
                //IWeiBee qq = GetWeiBeeGetByType(WeiBeeType.QQ);
                //WeiBeeQQ wb = qq as WeiBeeQQ;
                //wb.GetUserId();
                OpenWebPage("http://t.qq.com/");
            }
            else
            {
                IWeiBee qq = GetWeiBeeByType(WeiBeeType.QQ);
                Settings target = new Settings(qq.GetOAuth());
                bool? result = target.ShowDialog();
                if (result == true)
                {
                    var oauth = target.GetAuth();
                    qq.SetOAuth(oauth.Token, oauth.TokenSecret);
                    UpdateAccountWithWeiBee(qq);
                    MessageBox.Show("腾讯微博账号设置成功");
                }
            }
        }

        private void UpdateAccountWithWeiBee(IWeiBee wb)
        {
            var acc = accounts.First(a => a.UserType == wb.UserType);
            var oauth = wb.GetOAuth();
            acc.ConsumerKey = oauth.ConsumerKey;
            acc.ConsumerSecret = oauth.ConsumerSecret;
            acc.Token = oauth.Token;
            acc.TokenSecret = oauth.TokenSecret;
            accountHelper.SaveAccounts(accounts);
        }

        private void btSohu_Click(object sender, RoutedEventArgs e)
        {
            if (HasAccountType(WeiBeeType.Sohu))
            {
                OpenWebPage("http://t.sohu.com");
            }
            else
            {
                IWeiBee sohu = GetWeiBeeByType(WeiBeeType.Sohu);
                Settings target = new Settings(sohu.GetOAuth());
                bool? result = target.ShowDialog();
                if (result == true)
                {
                    var oauth = target.GetAuth();
                    sohu.SetOAuth(oauth.Token, oauth.TokenSecret);
                    UpdateAccountWithWeiBee(sohu);
                    MessageBox.Show("搜狐微博账号设置成功");
                }
            }
        }

        private void btSina_Click(object sender, RoutedEventArgs e)
        {
            if (HasAccountType(WeiBeeType.Sina))
            {
                OpenWebPage("http://weibo.com");
                //IWeiBee sina = GetWeiBeeGetByType(WeiBeeType.Sina);
                //OpenWebPage(string.Format("http://weibo.com/{0}",sina.GetUserId()));
            }
            else
            {
                IWeiBee sina = GetWeiBeeByType(WeiBeeType.Sina);
                SinaUser sinaUserForm = new SinaUser();
                bool? result = sinaUserForm.ShowDialog();
                if (result == true)
                {
                    var oauth = sinaUserForm.GetOAuth();
                    sina.SetOAuth(oauth.Token, oauth.TokenSecret);
                    UpdateAccountWithWeiBee(sina);
                    MessageBox.Show("新浪微博账号设置成功");
                }
            }
        }

        private void btSend_Click(object sender, RoutedEventArgs e)
        {
            messagetxt = tbText.Text;
            tbText.Text = string.Empty;
            bgwTwitter.RunWorkerAsync();
        }

        private void btPic_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new OpenFileDialog();
            dlg.FileName = "picture"; // Default file name
            dlg.DefaultExt = "*.*"; // Default file extension

            bool? result = dlg.ShowDialog();
            if (result == true)
            {
                imagefile = dlg.FileName;
            }
        }

        private bool HasAccountType(WeiBeeType weibeeType)
        {
            return weibees.Exists(weibee => weibee.IsEnabled && weibee.UserType == weibeeType);
        }

        private IWeiBee GetWeiBeeByType(WeiBeeType weiBeeType)
        {
            return weibees.First(weibee => weibee.UserType == weiBeeType);
        }

        public static void OpenWebPage(string url)
        {
            try
            {
                Process.Start(url);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
